// 实现这个项目的构建任务

const {src, dest, parallel, series, watch } = require('gulp')

const loadPlugins = require('gulp-load-plugins')
const browserSync = require('browser-sync')

const plugins = loadPlugins()
const del = require('del')
const browser = browserSync.create()

const data = {
    menus: [],
    pkg: require('./package.json'),
    data: new Date()
}
// 处理style文件
const style = () => {
    return src('src/assets/styles/*.scss', { base: 'src'})
    .pipe(plugins.sass())
    .pipe(dest('temp'))
}

// 处理js文件
const js = () => {
    return src('src/assets/scripts/*.js', { base: 'src'})
    .pipe(plugins.babel({presets: ['@babel/preset-env']}))
    .pipe(dest('temp'))
}

// 处理html文件
const html = () => {
    return src('src/*.html', { base: 'src'})
    .pipe(plugins.swig({data}))
    .pipe(dest('temp'))
}

// 处理图片文件
const image = () => {
    return src('src/assets/images/**', { base: 'src' } )
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 处理字体文件
const fonts = () => {
    return src('src/assets/fonts/**', { base: 'src' } )
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 处理public 目录
const public = () => {
    return src('public/**', { base: 'public' } )
    .pipe(dest('dist'))
}

// 删除文件
const clean = () => {
    return del(['dist'])
}

// 监听文件
const watchFIle = () => {
    watch('src/assets/styles/*.scss', style)
    watch('src/assets/scripts/*.js', js)
    watch('src/*.html', html)
    watch('src/assets/images/**', image)
    watch('src/assets/fonts/**', fonts)
    watch('public/**', public)
}

// 文件压缩
const useref = () => {
    return src('temp/*.html', { base: 'temp'})
    .pipe(plugins.useref({searchPath: ['temp', '.']}))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin(
        {
            collapseWhitespace: true,
            minifyCSS: true,
            minifyJS: true
        }
    )))
    .pipe(dest('dist'))
}

// 开发服务器
const server = () => {
    watchFIle()
    browser.init({
        notify: false, // 关闭browser提示
        port: 8090, // 端口
        files: 'dist/**',
        server: {
            baseDir: ['temp', 'src', 'public'],
            routes: {
                '/node_modules': 'node_modules'
            }
        }
    })
}

// 组合任务
const compile = parallel(html, js, style)

// 文件打包
const build = series(clean, parallel(series(compile, useref),image, fonts, public))

// 文件运行
const serve = series(compile, server)

// 导出
module.exports = {
    clean,
    build,
    serve,
}